#pragma once

#include <iostream>
#include "Protocol.hpp"


enum{
    DIV_ZERO = 1,
    MOD_ZERO,
    OTHER_OPER,
};

// 服务器处理请求功能封装
class ServerCal{
public:
    ServerCal()
    {}

    Response CalculatorHelper(const Request &req){
        Response resp(0, 0);
        switch(req._op){
            case '+':
                resp._result = req._x + req._y;
                break;
            case '-':
                resp._result = req._x - req._y;
                break;
            case '*':
                resp._result = req._x * req._y;
                break;
            case '/':{
                if(req._y == 0){
                    resp._code = DIV_ZERO;
                }
                else{
                    resp._result = req._x / req._y;
                }
            }
            break;
            case '%':{
                if(req._y == 0){
                    resp._code = MOD_ZERO;
                }
                else{
                    resp._result = req._x % req._y;
                }
            }
            break;
            default:
                resp._code = OTHER_OPER;
                break;
        }

        return resp;
    }
    std::string Calculator(std::string &package){
        Request req;
        std::string content;
        // 获取请求的有效载荷
        bool r = Decode(package, &content);     // 请求报文:"len\nx op y\n" ---> content: "x op y"
        if(!r){
            return "";
        }
        // 将请求报文反序列化
        r = req.Deserialize(content);           // content: "x op y" ---> req._x = x, req._y = y, req._op =op
        if(!r){
            return "";
        }

        content = "";
        // 处理请求报文 获取回应报文的结构化数据  
        Response resp = CalculatorHelper(req);  // 计算得到 resp._result, resp._code
        // 将响应报文序列化
        resp.Serialize(&content);               // resp._result, resp._code ---> "result code"
        // 添加报头
        content = Encode(content);              // "result code" ---> 响应报文:"len\nresult code\n"

        return content;
    }

    ~ServerCal()
    {}
};